package com.cavy.platform.server.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;

/**
 * Created by tangxu on 18-7-10.
 */
public final class FileUtils {

    private FileUtils() {
    }

    public static void delete(File file) {
        try {
            Files.delete(FileSystems.getDefault().getPath(file.getPath()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static File saveFile(MultipartFile image, String saveDir, String fileName) throws IOException {
        File filepath = new File(saveDir, fileName);
        File parentFile = filepath.getParentFile();
        if (!parentFile.exists()) {
            boolean mkdirs = parentFile.mkdirs();
            if (!mkdirs) {
                throw new IOException("创建文件夹:" + parentFile.getPath() + "失败");
            }
        }
        if (filepath.exists()) {
            Files.delete(FileSystems.getDefault().getPath(filepath.getPath()));
        }
        image.transferTo(filepath);
        return filepath;
    }

    public static Date getCreateTime(String fullFileName) {
        Path path = Paths.get(fullFileName);
        BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr;
        try {
            attr = basicview.readAttributes();
            return new Date(attr.creationTime().toMillis());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void delFolder(String folderPath) {
        File path = new File(folderPath);
        File[] files = path.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (!file.isDirectory()) {
                    delete(file);
                } else {
                    delFolder(file.getPath());
                }
            }
        }
        delete(path);
    }

    public static String getFileExt(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

}
